package cn.tedu._03vehicle.base.interceptors;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Configuration
public class RateLimitInterceptor implements HandlerInterceptor {
    private static final int MAX_REQUEST_COUNT = 3;
    private static final int MAX_REQUEST_WINDOW_SIZE=60;

    private final ConcurrentHashMap<String ,Integer> clientCounts =new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String , LocalDateTime> lastRequestTimes =new ConcurrentHashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("进入限流拦截器");
        String clientIp = request.getRemoteAddr();
        LocalDateTime lastTime =lastRequestTimes.get(clientIp);
        if (lastTime == null || LocalDateTime.now().isAfter(lastTime.plusSeconds(MAX_REQUEST_WINDOW_SIZE))) {
            clientCounts.put(clientIp, 0);
            lastRequestTimes.put(clientIp, LocalDateTime.now());
        }
        Integer i = clientCounts.get(clientIp);
        i =i+1;
        clientCounts.put(clientIp,i);
        if (i>MAX_REQUEST_COUNT){
            throw new RuntimeException("访问次数过多");
        }
       return true;
    }
}
